<?php
namespace app\mobile\controller;

use app\model\Theme; 

class Fanpai extends Base
{
    public function Fanpai()
    {
global $_G, $_P;
$system    = $_G['system'];
$fans = $this->checkuser();
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$themeid = intval($_P['themeid']);
// $theme = Theme::getThemeById($themeid);
$config = Theme::getConfig($themeid);
$weizhi = intval($_P['weizhi']);
$result = array();

$pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
$fans = db_find("SELECT * FROM ".tablename(t_fans)."
		WHERE themeid = :themeid and openid = :openid",$pm);
		
if($system['fanpai'] !=1 || $config['fanpaigroupid']==0){
	$result = array(
		"errcode"=>2,
		"msg"=>'翻牌功能未开启',
	);
	return_msg($result, '', 'ajax');
}

$choujianglist = db_select("SELECT giftid FROM ".tablename(t_fanpaichoujiang)."
		WHERE weizhi= " . $weizhi . " and  themeid = :themeid and openid = :openid",$pm);
if(!empty($choujianglist )){
	$result = array(
		"errcode"=>2,
		"msg"=>'参数错误2',
	);
	return_msg($result, '', 'ajax');
}

//已抽奖次数
$yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
		WHERE themeid = :themeid and openid = :openid",$pm);

if($yichou>= $config['fanpailimit'] || empty($fans['jihui'])){
	$result = array(
		"errcode"=>2,
		"msg"=>'抽奖机会已用完',
	);
	return_msg($result, '', 'ajax');
}

//已抽奖记录
$choujianglist = db_select("SELECT giftid FROM ".tablename(t_fanpaichoujiang)."
		WHERE themeid = :themeid and openid = :openid ORDER BY giftid",$pm);


foreach ($choujianglist as $index => $row) {
	if ($index==0) {
		$yichouid = $row['giftid'];
		$tiaojian = "id <> '{$yichouid}' and";
	} else {
		$yichouid = $yichouid . "','". $row['giftid'];
		$tiaojian = "id not in ('{$yichouid}') and";
	}
	
}

//未抽到的记录
$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
							WHERE {$tiaojian} giftgroupid = '{$config['fanpaigroupid']}' and state=1 and stock > 0 and zhongjianglv > 0 ORDER BY zhongjianglv desc";

// echo "未抽到的记录".$sql;
$giftlist = db_select ( $sql );

if(empty($giftlist)){
	$result = array(
		"errcode"=>2,
		"msg"=>'抱歉！您未抽中！',
	);
	return_msg($result, '', 'ajax');
}

$choujiang=array();
foreach ($giftlist as $index => $row) {
	if ($index==0) {
		array_push($choujiang,$row['id']);
		$zhongjianglv = $row['zhongjianglv'];
	} elseif($zhongjianglv == $row['zhongjianglv']) {
		array_push($choujiang,$row['id']);		
	}
}

//抽中的礼品ID
$giftid = $choujiang[rand(0,count($choujiang)-1)];
if(empty($giftid)){
	$result = array(
		"errcode"=>2,
		"msg"=>'未抽中',
	);
	return_msg($result, '', 'ajax');
}


$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
							WHERE id = '{$giftid}' ORDER BY displayorder ";
$gift = db_find ( $sql );

if($gift['stock']<1 ){
	$result = array(
		"errcode"=>2,
		"msg"=>'库存不足',
	);
	return_msg($result, '', 'ajax');
}


    $params = array();
    
    $params[':uid'] = $_G['member']['uid'];
    $params[':giftid'] = $giftid;
    $params[':themeid'] = $themeid;
    $friend = db_find("SELECT * FROM ".tablename(t_fanpaichoujiang)."
		WHERE uid = :uid and themeid = :themeid and giftid = :giftid",$params);

    // echo "抽中的礼品ID".$giftid;
	if(empty($friend)){
        $data = array(
            'themeid'   => $themeid,
            'uniacid'   => $_G['mpid'],
            'uid'       => $_G['member']['uid'],
            'openid'    => $_G['openid'],
            'nickname'  => $fans['nickname'],
            'avatar'    => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
            'status'    => 1,
            'addtime'   => TIMESTAMP,
            'giftid'  => $giftid,
            'giftname'  => $gift['giftname'],
            'giftimg'  => $gift['giftimg'],
            'weizhi'  => $weizhi,
        );

        $insertid = db_insert(t_fanpaichoujiang, $data);

		$pm = array(":themeid"=>$themeid,":uid"=>$_G['member']['uid']);
		
		db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui -1 WHERE themeid =:themeid and uid = :uid",$pm);

		db_query("UPDATE ".tablename(t_gift)." SET stock = stock - 1 WHERE id = " . $giftid );

		$result = array(
			"errcode"=>1,
			"msg"=>tomedia($gift['giftimg']),
			"successimg"=>tomedia($gift['giftimg2']),

		);
		return_msg($result, '', 'ajax');
    }else{
		$result = array(
			"errcode"=>2,
			"msg"=>'很遗憾，未抽中！',
		);
		return_msg($result, '', 'ajax');
    }
}
}